package org.firefly.controller;

import org.firefly.entity.TimeCapsule;
import org.firefly.entity.User;
import org.firefly.service.TimeCapsuleService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/api/capsules")
@RequiredArgsConstructor
public class TimeCapsuleController {

    private final TimeCapsuleService capsuleService;

    @PostMapping
    public ResponseEntity<TimeCapsule> createCapsule(
            @AuthenticationPrincipal User user,
            @RequestParam String title,
            @RequestParam String content,
            @RequestParam LocalDateTime openDate,
            @RequestParam String recipientEmail,
            @RequestParam(required = false) MultipartFile media) {

        try {
            TimeCapsule capsule = capsuleService.createCapsule(
                    user, title, content, openDate, recipientEmail, media);
            return ResponseEntity.ok(capsule);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @GetMapping
    public ResponseEntity<List<TimeCapsule>> getUserCapsules(@AuthenticationPrincipal User user) {
        return ResponseEntity.ok(capsuleService.getUserCapsules(user));
    }

    @GetMapping("/pending")
    public ResponseEntity<List<TimeCapsule>> getPendingCapsules(@AuthenticationPrincipal User user) {
        return ResponseEntity.ok(capsuleService.getPendingCapsules(user));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteCapsule(
            @AuthenticationPrincipal User user,
            @PathVariable Long id) {

        capsuleService.deleteCapsule(id);
        return ResponseEntity.noContent().build();
    }
}